package com.kkb.cubemall.product.aop.auth;

import com.kkb.cubemall.product.utils.JwtOperator;
import io.jsonwebtoken.Claims;
import lombok.RequiredArgsConstructor;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Objects;

/**
 * @ClassName AuthAspect
 * @Description
 * @Author hubin
 * @Date 2021/7/9 20:56
 * @Version V1.0
 **/
@Aspect
@Component
@RequiredArgsConstructor(onConstructor = @_(@Autowired))
public class AuthAspect {

    // 注入jwt工具类对象
    @Autowired
    private JwtOperator jwtOperator;

    @Autowired
    private HttpServletRequest request;

    @Around("@annotation(com.kkb.cubemall.product.aop.auth.CheckLogin)")
    public Object checkLogin(ProceedingJoinPoint proc) throws Throwable {
            // 校验token
            this.checkToken();
            // 调用业务方法
            return proc.proceed();
    }

    private void checkToken(){
        try {
            // 增强业务
            String token = request.getHeader("X-Token");

            // 校验token是否合法
            Boolean isValid = jwtOperator.validateToken(token);
            if(!isValid){
                throw new RuntimeException("token不合法!");
            }
            // 如果token校验成功的
            Claims claims = jwtOperator.getClaimsFromToken(token);
            // 获取用户身份信息，放入request对象
            request.setAttribute("id",claims.get("id"));
            request.setAttribute("username",claims.get("username"));
            request.setAttribute("role",claims.get("role"));
        } catch (RuntimeException e) {
            throw new RuntimeException("token不合法!");
        }

    }


    @Around("@annotation(com.kkb.cubemall.product.aop.auth.CheckAuthorization)")
    public Object checkAuthorization(ProceedingJoinPoint point) throws Throwable {

        try {
            // 校验token是否合法
            this.checkToken();

            // 获取角色
            String role = (String) request.getAttribute("role");

            // 获取注解的值，
            MethodSignature signature = (MethodSignature) point.getSignature();
            Method method = signature.getMethod();
            CheckAuthorization annotation = method.getAnnotation(CheckAuthorization.class);

            String value = annotation.value();

            // 注解角色是否相等
            if(!Objects.equals(role,value)){
                throw new RuntimeException("用户无访问权限");
            }
        } catch (RuntimeException e) {
            throw new RuntimeException("用户无访问权限");
        }

        return point.proceed();

    }








}

